// ignore_for_file: constant_identifier_names

import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/common_model/login_slider_model.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/net/api/common_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:oktoast/oktoast.dart';

enum VerificationCodeType {
  /// 注册
  REGISTER,

  /// 重置密码
  RESET_PASSWORD,

  /// 登录
  LOGIN,

  /// 重置支付密码
  RESET_SECURITY_PASSWORD,

  /// 转账
  TRANSFER,

  /// 艺术家创建
  ART_CREATE,

  /// 商家创建
  BUSINESS_CREATE,

  /// 管理员创建
  ADMIN_CREATE,
  // 图片验证码
  CODE_IMAGE,
  //支付
  PAY_ORDER,
  //注销
  LOGOUT,
}

class VerificationCodeWidet extends StatefulWidget {
  final int initialCount;
  final Function({String code, int? msgId})? onChanged;
  final Function()? textFun;
  final double? buttonRadio;
  final VerificationCodeType type;
  final String phoneNumber;
  final String? password;
  final String hintText;
  final String? lableTitle;
  final String? codeImageUrl;
  final bool sendMsg;
  final FocusNode? focusNode;

  const VerificationCodeWidet({
    super.key,
    required this.initialCount,
    this.onChanged,
    this.buttonRadio = 8,
    this.lableTitle,
    required this.type,
    required this.phoneNumber,
    this.hintText = '请输入',
    this.codeImageUrl,
    this.textFun,
    this.sendMsg = false,
    this.password,
    this.focusNode,
  });

  @override
  State<VerificationCodeWidet> createState() => _VerificationCodeWidetState();
}

class _VerificationCodeWidetState extends State<VerificationCodeWidet> {
  final TextEditingController _controller = TextEditingController();
  Timer? _timer;
  int _remainingTime = 0;
  int? _msgId;
  String btnText = '获取验证码';
  final ValueNotifier<double> sliderNotifier = ValueNotifier<double>(0);
  final ValueNotifier<double> sliderImg = ValueNotifier<double>(0);
  final sliderDetail = Rx<LoginSliderModel?>(null);
  final backImage = Rx<Uint8List?>(null);
  final slidingImage = Rx<Uint8List?>(null);
  String? paramsType;
  double maxWidth = 0;
  double rate = 0;
  double maxKnobOffset = 0;

  Uint8List convertBase64ToUint8List(base64Str) {
    return base64Decode(base64Str.split(',').last);
  }

  @override
  void initState() {
    super.initState();
    _remainingTime = widget.initialCount;
    if (widget.type == VerificationCodeType.LOGOUT) {
      paramsType = 'ACCOUNT_CANCELLATION';
    } else {
      paramsType =
          widget.type == VerificationCodeType.LOGIN
              ? 'LOGIN'
              : (widget.type == VerificationCodeType.RESET_PASSWORD
                  ? 'RESET_PASSWORD'
                  : 'RESET_SECURITY_PASSWORD');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        widget.lableTitle != null
            ? Padding(
              padding: const EdgeInsets.fromLTRB(0, 0, 0, 8),
              child: Text(
                widget.lableTitle!,
                style: TextStyle(
                  fontSize: 14.px,
                  color: AppColors.fontColorBlack,
                ),
              ),
            )
            : SizedBox(),
        Container(
          height: 45.px,
          decoration: BoxDecoration(
            color:
                widget.type == VerificationCodeType.LOGOUT
                    ? AppColors.backgroundColorGreyF8
                    : AppColors.backgroundColorBlackLight,
            borderRadius: BorderRadius.circular(widget.buttonRadio!),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(21, 0, 0, 0),
                  child: TextField(
                    focusNode: widget.focusNode,
                    onSubmitted: (_) => FocusScope.of(context).unfocus(),
                    controller: _controller,
                    keyboardType: TextInputType.number,
                    style: TextStyle(
                      fontSize: 14.px,
                      color: AppColors.fontColor,
                    ),
                    maxLength: 6,
                    onChanged: _onChanged,
                    decoration: InputDecoration(
                      counterText: '',
                      hintText: widget.hintText,
                      hintStyle: TextStyle(color: AppColors.fontColorGray99),
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ),
              widget.type == VerificationCodeType.CODE_IMAGE
                  ? Row(
                    children: [
                      LazyImage(
                        imageUrl: 'static/images/my_bg.png',
                        width: 111,
                        height: 45,
                        borderRadius: 10,
                      ),
                      hiSpace(width: 6),
                    ],
                  )
                  : Text(''),
              widget.type == VerificationCodeType.LOGIN ||
                      widget.type == VerificationCodeType.RESET_PASSWORD ||
                      widget.type ==
                          VerificationCodeType.RESET_SECURITY_PASSWORD ||
                      widget.type == VerificationCodeType.REGISTER ||
                      widget.type == VerificationCodeType.PAY_ORDER ||
                      widget.type == VerificationCodeType.LOGOUT
                  ? Row(
                    children: [
                      TextButton(
                        onPressed: () {
                          _remainingTime < 60
                              ? null
                              : _getCodeImageUrl(context: context);
                        },
                        child: Text(
                          _remainingTime < 60 ? '$_remainingTime秒后重试' : btnText,
                          style: TextStyle(
                            fontSize: 12.px,
                            color:
                                _remainingTime < 60
                                    ? AppColors.backgroundColorGreenLight
                                    : AppColors.backgroundColorGreenLight,
                          ),
                        ),
                      ),
                      hiSpace(width: 12),
                    ],
                  )
                  : Text(''),
            ],
          ),
        ),
      ],
    );
  }

  _buildContent(BuildContext context) {
    return Builder(
      builder: (BuildContext context) {
        return LayoutBuilder(
          builder: (context, constraints) {
            consoleLog('${double.infinity}-----');
            // 计算拖动滑块计算x轴位移像素
            maxWidth = constraints.maxWidth;
            if (sliderDetail.value != null) {
              // 计算比例
              var originalWidth = sliderDetail.value?.originalWidth;
              rate = maxWidth / originalWidth!;
              consoleLog(
                '${maxWidth}----maxWidth-----${rate}---rate----${originalWidth}',
              );
              // // 这是灰色背景条的宽度: dialogContentWidth - 边距（上下等大无边距 同为maxWidth）
              final effectiveTrackWidth = maxWidth;
              // // 滑块的宽度
              final knobWidth = sliderDetail.value!.sliderWidth! * rate;
              // 确保 maxKnobOffset 不为负数。如果轨道比滑块窄，则 maxKnobOffset 为 0。
              maxKnobOffset = (effectiveTrackWidth - knobWidth).clamp(
                0.0,
                maxWidth,
              );
            }

            return SingleChildScrollView(
              child: Column(
                children: [
                  Obx(
                    () => Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(4),
                        color: Colors.white,
                      ),
                      constraints: BoxConstraints(maxHeight: 300.px),
                      clipBehavior: Clip.antiAlias,
                      child: Stack(
                        alignment: Alignment.centerLeft,
                        children: [
                          LayoutBuilder(
                            builder: (context, constraints) {
                              return Image.memory(
                                backImage.value as Uint8List,
                                width:
                                    sliderDetail.value!.originalWidth! * rate,
                                height:
                                    sliderDetail.value!.originalHeight! * rate,
                                fit: BoxFit.fitHeight,
                              );
                            },
                          ),
                          Positioned(
                            left: 0,
                            top: sliderDetail.value!.randomY! * rate,
                            child: ValueListenableBuilder<double>(
                              valueListenable: sliderImg,
                              builder: (context, value, _) {
                                return Transform.translate(
                                  offset: Offset(value, 0),
                                  child: Image.memory(
                                    slidingImage.value as Uint8List,
                                    height:
                                        sliderDetail.value!.sliderWidth! * rate,
                                    width:
                                        sliderDetail.value!.sliderHeight! *
                                        rate,
                                    fit: BoxFit.fitHeight,
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 20.px),
                    height: 60,
                    child: Stack(
                      alignment: Alignment.center,
                      children: [
                        // 滑动轨道
                        Container(
                          width: double.infinity,
                          padding: EdgeInsets.only(left: 35),
                          height: 53,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(318),
                            border: Border.all(
                              color: Color(0xFFE7E7E7),
                              width: 1,
                            ),
                          ),
                          child: Text(
                            '拖动滑块 完成拼图',
                            style: TextStyle(
                              fontSize: 18.px,
                              color: AppColors.fontColorGreyLight,
                            ),
                          ),
                        ),

                        // 滑块
                        ValueListenableBuilder<double>(
                          valueListenable: sliderNotifier,
                          builder: (context, value, _) {
                            return Positioned(
                              left: value,
                              top: 0,
                              child: GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onHorizontalDragUpdate: (details) {
                                  final double currentOffset =
                                      sliderNotifier.value;
                                  // 计算新的偏移量，并将其限制在有效范围 [0, maxKnobOffset] 内
                                  final double newOffset = (currentOffset +
                                          details.delta.dx)
                                      .clamp(0.0, maxKnobOffset);
                                  sliderNotifier.value =
                                      newOffset < 0 ? 0 : newOffset;
                                  sliderImg.value =
                                      newOffset < 0 ? 0 : newOffset;
                                },
                                onHorizontalDragEnd: (_) async {
                                  // 滑动结束后发送接口验证，服务端根据正确x轴坐标和传入x轴坐标进行对比，完成校验
                                  var xPos =
                                      (sliderImg.value / maxWidth) *
                                      (sliderDetail.value?.originalWidth ?? 0);
                                  getSliderxPos(paramsType, xPos).then(
                                    (res) => {
                                      if (res.successful)
                                        {
                                          Navigator.of(context).pop(),
                                          startTimer(),
                                        }
                                      else
                                        {
                                          _getCodeImageUrl(
                                            context: context,
                                            isRefresh: 'update',
                                          ),
                                        },
                                    },
                                  );
                                },
                                child: ImageAssetWidget(
                                  imageUrl: 'static/images/slider_ico.png',
                                  width: 60,
                                  height: 60,
                                ),
                              ),
                            );
                          },
                        ),
                      ],
                    ),
                  ),
                  // hiSpace(height: 20.px),
                  // Text('data'),
                ],
              ),
            );
          },
        );
      },
    );
    // 原需求的图片验证码
    // return Builder(
    //   builder: (BuildContext context) {
    //     return Column(
    //       crossAxisAlignment: CrossAxisAlignment.start,
    //       children: [
    //         Container(
    //           height: 55.px,
    //           decoration: BoxDecoration(
    //             color: AppColors.backgroundColorGreyBold,
    //             borderRadius: BorderRadius.circular(8),
    //           ),
    //           child: Row(
    //             mainAxisAlignment: MainAxisAlignment.center,
    //             children: [
    //               Expanded(
    //                 child: Padding(
    //                   padding: const EdgeInsets.fromLTRB(21, 0, 0, 0),
    //                   child: TextField(
    //                     controller: _controller,
    //                     keyboardType: TextInputType.number,
    //                     style: TextStyle(
    //                       fontSize: 15.px,
    //                       color: AppColors.fontColorBlack,
    //                     ),
    //                     maxLength: 6,
    //                     onChanged: _onCodeChanged,
    //                     decoration: InputDecoration(
    //                       counterText: '',
    //                       hintText: '请输入',
    //                       hintStyle: TextStyle(
    //                         color: AppColors.fontColorGreyLight,
    //                       ),
    //                       border: InputBorder.none,
    //                     ),
    //                   ),
    //                 ),
    //               ),
    //               Row(
    //                 children: [
    //                   GestureDetector(
    //                     onTap: () {
    //                       _getCodeImageUrl(type: 'update');
    //                     },
    //                     child: Obx(() {
    //                       return LazyImage(
    //                         imageUrl: imgCodeUrl.value,
    //                         width: 111,
    //                         height: 45,
    //                         borderRadius: 10,
    //                       );
    //                     }),
    //                   ),

    //                   hiSpace(width: 6),
    //                 ],
    //               ),
    //             ],
    //           ),
    //         ),
    //         Container(height: 6.px),
    //         Column(
    //           children: [
    //             Row(
    //               mainAxisAlignment: MainAxisAlignment.end,
    //               children: [
    //                 GestureDetector(
    //                   onTap: () {
    //                     _getCodeImageUrl(type: 'update');
    //                   },
    //                   child: Text('看不清？'),
    //                 ),
    //               ],
    //             ),
    //             hiSpace(height: 5.px),
    //             ButtonWidget(
    //               label: '确定',
    //               height: 32,
    //               width: 96,
    //               fontSize: 12.px,
    //               onPressed: () {
    //                 // if (widget.type == VerificationCodeType.CODE_IMAGE) {
    //                 //   LoginController controller = Get.find();
    //                 //   controller.isSendMsg.value = true;
    //                 // }
    //                 Navigator.of(context).pop();
    //                 startTimer();
    //               },
    //             ),
    //             // hiSpace(height: 15.px),
    //           ],
    //         ),
    //       ],
    //     );
    //   },
    // );
  }

  void startTimer() {
    String? templateEnum = '';
    if (widget.type == VerificationCodeType.LOGOUT) {
      templateEnum = 'ACCOUNT_CANCELLATION';
    } else {
      templateEnum =
          paramsType == 'RESET_SECURITY_PASSWORD'
              ? 'SECURITY_PASSWORD'
              : paramsType;
    }
    http.netFetch<dynamic>(
      CommonApi.sendMsg,
      params: {
        'mobile': widget.phoneNumber,
        'templateEnum': templateEnum,
        'uuid': HiCache.getInstance().get(GlobalController.uuid),
        'verificationEnums': paramsType,
      },
      success: (r) {
        _msgId = r.data?['msgId'];
        // 避免获取验证码时 输入框不重新出发 取不到msgId
        widget.onChanged!(code: '', msgId: _msgId);

        setState(() {
          _remainingTime--;
        });
        _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
          setState(() {
            if (_remainingTime > 0) {
              _remainingTime--;
            } else {
              btnText = '重新获取';
              _timer?.cancel();
              _remainingTime = widget.initialCount;
            }
          });
        });
      },
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    _controller.dispose();
    super.dispose();
  }

  void _onChanged(String value) {
    widget.onChanged!(code: value, msgId: _msgId);
  }

  // 传递滑块x轴距离
  Future getSliderxPos(type, xPos) async {
    var dis = xPos.round();
    return await http.netFetch(
      '${CommonApi.getSlider}/$type?xPos=$dis',
      success: (result) {},
    );
  }

  // 获取滑块图片
  Future getSlider(type) async {
    return await http.netFetch<LoginSliderModel>(
      '${CommonApi.getSlider}/$type',
      method: Method.get,
      success: (result) {},
    );
  }

  void _getCodeImageUrl({context, isRefresh}) {
    consoleLog('${widget.phoneNumber}----widget.phoneNumber');

    if (widget.type == VerificationCodeType.LOGOUT) {
      if (widget.password != null && widget.password!.isEmpty) {
        showToast('请输入登录密码');
        return;
      }
    } else {
      if (widget.phoneNumber.isEmpty) {
        showToast('请输入手机号');
        return;
      }
      if (widget.phoneNumber.length < 11) {
        showToast('请输入正确的手机号');
        return;
      }
    }
    var codeType = '';

    switch (widget.type) {
      case VerificationCodeType.LOGIN: // 验证码登录
        codeType = 'LOGIN';
      case VerificationCodeType.RESET_PASSWORD:
        codeType = 'RESET_PASSWORD';
      case VerificationCodeType.RESET_SECURITY_PASSWORD:
        codeType = 'RESET_SECURITY_PASSWORD';
      case VerificationCodeType.LOGOUT:
        codeType = 'ACCOUNT_CANCELLATION';
      default:
        return;
    }
    getSlider(codeType).then(
      (res) => {
        if (res.successful)
          {
            sliderDetail.value = res.data!,
            backImage.value = convertBase64ToUint8List(res.data!.backImage),
            slidingImage.value = convertBase64ToUint8List(
              res.data!.slidingImage,
            ),
            if (isRefresh != 'update') _showCodeSheet(context),
            sliderNotifier.value = 0,
            sliderImg.value = 0,
          },
      },
    );
  }

  void _onCodeChanged(val) {
    // 图形验证码
  }

  _showCodeSheet(BuildContext context) {
    showConfirmDialog(
      context: context,
      showRefreshIco: true,
      message: '安全验证',
      closeButton: true,
      inputCode: true,
      fontSize: 18,
      fontTitleColor: AppColors.fontColor21,
      children: [
        _buildContent(context),
        // Text('-3094857'),
      ],
      actions: [],
      onPressed: () {
        // 刷新图片
        _getCodeImageUrl(context: context, isRefresh: 'update');
        sliderNotifier.value = 0;
        sliderImg.value = 0;
      },
    );
  }
}
